package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;

import net.bytebuddy.matcher.CollectionOneToOneMatcher;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private UserServiceImpl userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;

    /**
     * 查看评价详情
     * @param id
     * @return
     */
    @Override
    public Result queryBlog(Long id) {
        // 查询评价信息
        Blog blog = getById(id);
        if(blog == null){
            return Result.fail("消息不存在！");
        }
        // 查询用户信息
        setUserService(blog);
        setBlogLiked(blog);
        return Result.ok(blog);
    }

    /**
     * 是否已经点赞
     * @param blog
     */
    private void setBlogLiked(Blog blog) {
        String key = BLOG_LIKED_KEY+blog.getId();
        UserDTO user = UserHolder.getUser();
        if(user == null ){
            return;
        }
        Long userId = user.getId();
        // 是否点过赞
        Double isLiked = stringRedisTemplate.opsForZSet()
                .score(key,userId.toString());
        blog.setIsLike(BooleanUtil.isTrue(isLiked != null));
    }

    /**
     * 设置用户信息
     * @param blog
     */
    private void setUserService(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    /**
     * 分页查询
     * @param current
     * @return
     */
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.setBlogLiked(blog);
            this.setUserService(blog);
        });
        return Result.ok(records);
    }

    /**
     * 点赞功能
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        String key = BLOG_LIKED_KEY+id;
        Long userId = UserHolder.getUser().getId();
        Blog blog = getById(id);
        // 用户是否点过赞
        Double isLiked = stringRedisTemplate.opsForZSet()
                .score(key,userId.toString());
        if(isLiked != null){
            // 点过赞了，则取消点赞
            boolean update = update().setSql("liked = liked - 1").eq("id",id).update();
            if(update){
                //修改成功,redis里删除用户记录
                stringRedisTemplate.opsForZSet().remove(key, String.valueOf(userId));
            }
        }else{
            // 没有点过赞，则点赞+1
            boolean update = update().setSql("liked = liked + 1").eq("id",id).update();
            if(update){
                //修改成功,redis里添加用户记录
                stringRedisTemplate.opsForZSet().add(key, String.valueOf(userId),
                        System.currentTimeMillis());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key = BLOG_LIKED_KEY+id;
        // 获取点赞队列
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(top5 == null || top5.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        // 2.解析出其中的用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
        // 3.根据用户id查询用户 WHERE id IN ( 5 , 1 ) ORDER BY FIELD(id, 5, 1)
        List<UserDTO> userDTOS = userService.query()
                .in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        // 4.返回
        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);
        if(!isSuccess){
            return Result.fail("保存博客失败！");
        }
        // 把id推送给粉丝
        // 获取所有粉丝
        List<Follow> followList = followService.query()
                .eq("follow_user_id", blog.getUserId()).list();

        // 获取所有粉丝id
        String key = "feed:";
        for (Follow follow : followList) {
            stringRedisTemplate.opsForZSet().add(key+follow.getUserId(),blog.getId().toString()
                    ,System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    /**
     * 查询关注用户发的博客
     * @param max
     * @param offSet
     * @return
     */
    @Override
    public Result followBlog(Long max, Integer offSet) {
        Long userId = UserHolder.getUser().getId();
        String key = "feed:" + userId;
        // 查询推送的博客，最小：0，最大max,上一次查询最小重复offSet个，每次查询数据2条
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate
                .opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offSet, 2);
        // 判断是否为空
        if(typedTuples == null || typedTuples.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        // 解析
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int size = 1;

        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            // 获取id
            String value = typedTuple.getValue();
            ids.add(Long.valueOf(value));
            // 获取时间戳
            long time = typedTuple.getScore().longValue();
            if(time == minTime){
                size++;
            }else{
                minTime = time;
                size=1;
            }
        }
        // 获取博客信息
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids)
                .last("ORDER BY FIELD(id," + idStr + ")").list();
        // 完善信息
        for (Blog blog : blogs) {
            setBlogLiked(blog);
            setUserService(blog);
        }
        // 封装答案
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(size);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }
}
